<!DOCTYPE html>
<html lang="zh" xmlns:th="http://www.thymeleaf.org" xmlns:shiro="http://www.pollix.at/thymeleaf/shiro">
<head>
    <th:block th:include="common/include :: header('服务结算单消费明细')"/>
</head>
<body>
<div class="ui-layout-center">
    <div class="col-sm-12 search-collapse">
        <div class="col-sm-12">
            <div class="col-sm-6">
                <div class="form-group">
                    <label class="col-sm-6 control-label">客户姓名：</label>
                    <label class="col-sm-6 control-label">[[${statement.customerName}]]</label>
                </div>
            </div>
            <div class="col-sm-6">
                <div class="form-group">
                    <label class="col-sm-6 control-label">联系方式：</label>
                    <label class="col-sm-6 control-label">[[${statement.customerPhone}]]</label>
                </div>
            </div>
        </div>
        <div class="col-sm-12">

            <div class="col-sm-6">
                <div class="form-group">
                    <label class="col-sm-6 control-label">车牌号码：</label>
                    <label class="col-sm-6 control-label">[[${statement.licensePlate}]]</label>
                </div>
            </div>
            <div class="col-sm-6">
                <div class="form-group">
                    <label class="col-sm-6 control-label">汽车类型：</label>
                    <label class="col-sm-6 control-label">[[${statement.carSeries}]]</label>
                </div>
            </div>
        </div>
        <div class="col-sm-12">
            <div class="col-sm-6">
                <div class="form-group">
                    <label class="col-sm-6 control-label">服务类型：</label>
                    <label class="col-sm-6 control-label">[[${@dict.getLabel('si_service_catalog',statement.serviceType)}]]</label>
                </div>
            </div>
            <div class="col-sm-6">
                <div class="form-group">
                    <label class="col-sm-6 control-label">到店时间：</label>
                    <label class="col-sm-6 control-label"
                           th:text="${#dates.format(statement.actualArrivalTime, 'yyyy-MM-dd HH:mm')}"></label>
                </div>
            </div>
        </div>
        <div class="col-sm-12">
            <div class="col-sm-6">
                <div class="form-group">
                    <label class="col-sm-6 control-label">总消费金额：</label>
                    <label class="col-sm-6 control-label" id="totalAmount">[[${statement.totalAmount}]]</label>
                </div>
            </div>
            <div class="col-sm-6">
                <div class="form-group">
                    <label class="col-sm-6 control-label">实付价格：</label>
                    <label class="col-sm-6 control-label" id="actuallyPaid">[[${statement.totalAmount-statement.discountAmount}]]</label>
                </div>
            </div>
        </div>
        <div class="col-sm-12">
            <div class="col-sm-6">
                <div class="form-group">
                    <label class="col-sm-6 control-label">优惠价格：</label>
                    <input class="col-sm-6" type="number" onchange="discountFun()" id="discountAmount" name="discountAmount"
                           th:field="${statement.discountAmount}"/>
                </div>
            </div>
        </div>
    </div>
    <div class="btn-group-sm" id="item-toolbar" role="group">
        <a id="saveBtn" class="btn btn-success disabled" onclick="saveFun()"
           shiro:hasPermission="business:statementItem:add">
            <i class="fa fa-plus"></i> 保存
        </a>
        <a id="payBtn" class="btn btn-info" onclick="payFun()"
           shiro:hasPermission="business:statementItem:payStatement">
            <i class="fa fa-cc-visa"></i> 确认支付
        </a>
    </div>

    <div class="col-sm-12 select-table table-striped">
        <table id="statementItem-table"></table>
    </div>
</div>

<div class="ui-layout-east">
    <div class="col-sm-12 search-collapse">
        <form id="post-form">
            <div class="select-list">
                <ul>
                    <li>
                        名称：<input type="text" name="name"/>
                    </li>
                    <li>
                        是否套餐：
                        <select name="carPackage" th:with="type=${@dict.getType('si_car_package')}">
                            <option value="">所有</option>
                            <option th:each="dict : ${type}" th:text="${dict.label}" th:value="${dict.value}"></option>
                        </select>
                    </li>
                    <li>
                        服务分类：
                        <select name="serviceCatalog" th:with="type=${@dict.getType('si_service_catalog')}">
                            <option value="">所有</option>
                            <option th:each="dict : ${type}" th:text="${dict.label}" th:value="${dict.value}"></option>
                        </select>
                    </li>
                    <li>
                        <a class="btn btn-primary btn-rounded btn-sm" onclick="$.table.search()"><i
                                class="fa fa-search"></i>&nbsp;搜索</a>
                        <a class="btn btn-warning btn-rounded btn-sm" onclick="$.form.reset()"><i
                                class="fa fa-refresh"></i>&nbsp;重置</a>
                    </li>
                </ul>
            </div>
        </form>
    </div>

    <div class="col-sm-12 select-table table-striped">
        <table id="serviceItem-table"></table>
    </div>
</div>
<th:block th:include="common/include :: footer"/>
<th:block th:include="common/include :: layout-latest"/>
<script type="text/javascript">
    $(document).ready(function () {
        $('body').layout({applyDemoStyles: true});
    });
    // OUTER-LAYOUT
    $('body').layout({
        east__size: '35%',
    });
</script>
</body>
<script th:inline="javascript">
    $(function () {
        var options = {
            url: ctx + "/business/serviceItem/query?saleStatus=1",
            modalName: "服务单项",
            id: "serviceItem-table",
            uniqueId:"id",
            columns: [
                {
                    field: 'id',
                    title: '服务项id',
                    visible: false
                },
                {
                    field: 'name',
                    title: '服务项名称',
                    sortable: true
                },

                {
                    field: 'discountPrice',
                    title: '服务项折扣价',
                    sortable: true
                },
                {
                    field: 'info',
                    title: '备注信息',
                    sortable: true,
                    formatter: function (value, row, index) {
                        return $.table.tooltip(value, 10, "open");
                    }
                },
                {
                    title: '操作',
                    align: 'center',
                    formatter: function (value, row, index) {
                        var actions = [];
                        actions.push('<a class="btn btn-info btn-xs" href="javascript:void(0)" ' +
                            'onclick="addItemToStatementItem(\'' + row.id + '\')"><i class="fa fa-plus"></i></a> ');
                        return actions.join('');
                    }
                }]
        };
        $.table.init(options);
    });


    $(function () {
        var statementId = [[${statement.id}]];
        var options = {
                url: ctx + "/business/statementItem/query?statementId=" + statementId,
                modalName: "服务结算单",
                id: "statementItem-table",
                toolbar: "item-toolbar",
                uniqueId: "itemId",
                columns: [
                    {
                        field: 'itemName',
                        title: '服务项名称',
                        sortable: true
                    },

                    {
                        field: 'itemPrice',
                        title: '服务项价格',
                        sortable: true
                    },
                    {
                        field: 'itemQuantity',
                        title: '购买数量',
                        sortable: true,
                    },
                    {
                        title: '操作',
                        align: 'center',
                        formatter: function (value, row, index) {
                            var actions = [];
                            actions.push('<a class="btn btn-info btn-xs" href="javascript:void(0)" ' +
                                'onclick="addStatementItem(\'' + row.itemId + '\')"><i class="fa fa-plus"></i></a> ');
                            actions.push('<a class="btn btn-danger btn-xs" href="javascript:void(0)" ' +
                                'onclick="subStatementItem(\'' + row.itemId + '\')"><i class="fa fa-minus"></i></a> ');
                            return actions.join('');
                        }
                    }]
            }
        ;
        $.table.init(options);
    });

    function addItemToStatementItem(id) {
        var rs = $('#serviceItem-table').bootstrapTable('getRowByUniqueId',id);

        var statementItem = $('#statementItem-table').bootstrapTable('getRowByUniqueId',id);

        if (statementItem) {
            $('#statementItem-table').bootstrapTable('updateByUniqueId', {
                id: id,
                row: {
                    itemName:statementItem.itemName,
                    itemPrice: statementItem.itemPrice,
                    itemQuantity: statementItem.itemQuantity + 1
                }
            });
        }else {
            var newData = {"itemId":rs.id,"itemName":rs.name,"itemPrice":rs.discountPrice,"itemQuantity":1}
            $('#statementItem-table').bootstrapTable('append', newData);
        }
        discountFun();
    }

    function addStatementItem(id) {
        var statementItem = $('#statementItem-table').bootstrapTable('getRowByUniqueId',id);

        $('#statementItem-table').bootstrapTable('updateByUniqueId', {
            id: id,
            row: {
                itemName:statementItem.itemName,
                itemPrice: statementItem.itemPrice,
                itemQuantity: statementItem.itemQuantity + 1
            }
        });
        discountFun();
    }

    function subStatementItem(id) {
        var statementItem = $('#statementItem-table').bootstrapTable('getRowByUniqueId',id);

        if (statementItem.itemQuantity > 1) {
            $('#statementItem-table').bootstrapTable('updateByUniqueId', {
                id: id,
                row: {
                    itemName:statementItem.itemName,
                    itemPrice: statementItem.itemPrice,
                    itemQuantity: statementItem.itemQuantity - 1
                }
            });
        }else {
            $('#statementItem-table').bootstrapTable('removeByUniqueId',id);
        }
        discountFun();
    }

    function discountFun() {
        // 获取statementItem表所有的数据,计算总金额
        var data= $('#statementItem-table').bootstrapTable('getData',false);
        var totalAmount = 0;
        $.each(data,function (index,domEle) {
            totalAmount += domEle.itemPrice * domEle.itemQuantity;
        });

        $('#actuallyPaid').html(totalAmount);

        // 获取优惠价格
        var discountAmount = $('#discountAmount').val();
        if (discountAmount < 0 || discountAmount == '') {
            discountAmount = 0;
        }

        if (discountAmount > totalAmount) {
            $('#discountAmount').val(0);
            $.modal.alert("优惠金额不能大于总金额");
            return;
        }

        // 计算实付价格
        var actualPrice = totalAmount - discountAmount;

        // 修改 总金额、实付价格
        $('#actuallyPaid').html(actualPrice);
        $('#totalAmount').html(totalAmount);
        $('#discountAmount').val(discountAmount);

        // 按钮变化
        $('#saveBtn').removeClass("disabled");
        $('#payBtn').addClass("disabled");
    }

    function saveFun() {
        var statementId = [[${statement.id}]];
        // 获取表中所有的数据，并且往JSON的每个元素加入statementId
        var data= $('#statementItem-table').bootstrapTable('getData',false);
        $.each(data,function (index,domEle) {
            domEle.statementId = statementId;
        });

        // 获取优惠价格
        var discountAmount = $('#discountAmount').val();

        // 把优惠价格和rows一起传到后台
        var rows = {"discountAmount":discountAmount,list:data};

        var config = {
            url: ctx + "/business/statementItem/saveItems?statementId="+statementId,
            type: 'post',
            dataType: 'json',
            contentType:"application/json",
            data: JSON.stringify(rows),
            beforeSend: function () {
                $.modal.loading("正在处理中，请稍后...");
            },
            success: function(result) {
                $("#saveBtn").addClass("disabled");
                $("#payBtn").removeClass("disabled");
                $.operate.ajaxSuccess(result);
            }
        };
        $.ajax(config)
    }

    function payFun() {
        var statementId = [[${statement.id}]];
        $.modal.confirm("确定支付吗？",function () {
            $.operate.get("/business/statement/pay?statementId=" + statementId,function (result){
                if(result.code==web_status.SUCCESS){
                    $("#payBtn").addClass("disabled");
                    url = "/business/statementItem/itemDetail?statementId="+statementId;
                    $.modal.openTab("结算单明细", url,true);
                }else{
                    $.modal.alertError(result.msg)
                }
            })
        })
    }
</script>
</html>